// routes/users.js

const JWT = require('jsonwebtoken');
const Joi = require('joi');
const models = require('../models');

const GROUP_NAME = 'users';

module.exports = [{
  method: 'POST',
  path: `/${GROUP_NAME}/createJWT`,
  handler: async (request, reply) => {
    const generateJWT = (jwtInfo) => {
      const payload = {
        userId: jwtInfo.userId,
        exp: Math.floor(new Date().getTime() / 1000) + 7 * 24 * 60 * 60,
      };
      return JWT.sign(payload, process.env.JWT_SECRET);
    };
    reply({
        jwt_result: generateJWT({
            userId: 'aima-electric',
        })
    });
  },
  config: {
    tags: ['api', GROUP_NAME],
    description: '用于测试的用户 JWT 签发',
    auth: false, // 约定此接口不参与 JWT 的用户验证，会结合下面的 hapi-auth-jwt 来使用
  },
},{
  method: 'POST',
  path: `/${GROUP_NAME}/login`,
  handler: async (request, reply) => {
    let info = request.payload;
    let queryParams = {
        attributes: [
            'id',
            'operatorName',
            'userId',
            'password'
        ]
    };
    Object.assign(queryParams,{
      where: {
          userId: info.userId
      }
    })
    const {
        rows: results,
        count: totalCount
    } = await models.operators.findAndCountAll(queryParams);
    if(totalCount <= 0)
      reply({
        errorCode: -1,
        errorMessage: '无此用户',
        jwt_result: ''
      });
    else {
      if(results[0].password === request.payload.password){
        const generateJWT = (jwtInfo) => {
          const payload = {
            userId: jwtInfo.userId
          };
          return JWT.sign(payload, process.env.JWT_SECRET,{
            expiresIn: '1d'
          });
        };
        reply({
            errorCode: 0,
            errorMessage: 'success',
            jwt_result: generateJWT({
                userId: request.payload.userId,
            })
        });
      }else {
        reply({
          errorCode: -2,
          errorMessage: '密码不正确',
          jwt_result: ''
        });
      }
    }
  },
  config: {
    tags: ['api', GROUP_NAME],
    description: '用户登录，爱玛电动车登陆接口',
    auth: false, // 约定此接口不参与 JWT 的用户验证，会结合下面的 hapi-auth-jwt 来使用
    validate: {
      payload: {
        userId: Joi.string().required(),
        password: Joi.string().required()
      }
    }
  },
}];